//
//  CHATViewController.m
//  LiaoTianShi
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 菲克. All rights reserved.
//

#import "CHATViewController.h"

#import <AVOSCloud.h>
#import <AVOSCloudIM.h>
#import "ChatModel.h"
#import <UIImageView+WebCache.h>


@interface CHATViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>

@property(nonatomic,strong)UITableView *tabelView ;

@property (weak, nonatomic) IBOutlet UIButton *Button;



@property(nonatomic,strong)ChatModel *cr ;
@property(nonatomic,strong)NSMutableArray *messageArray ;
@property(nonatomic,strong)NSTimer * timmer;

@end

@implementation CHATViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    _cr = [ChatModel shareChatRoomHandle];
    
    _messageArray =_cr.messageArray ;
    
    // 设置返回按钮以及动作
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"退出聊天室" style:UIBarButtonItemStyleDone target:self action:@selector(quitAction:)];
    
    _tabelView =[[UITableView alloc] initWithFrame:CGRectMake(0,64,self.view.frame.size.width  ,self.view.frame.size.height- self.Button.frame.size.height-15) style:(UITableViewStylePlain)];
    _tabelView.delegate =self ;
    _tabelView.dataSource =self;
    //
    //取消分割线
    self.tabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    //取消table行选中
    self.tabelView.allowsSelection = NO;
    
    // 设置table的背景色
    self.tabelView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0];
    //设置文本框左边的一段空白
    self.messageTextField.leftView = [[UIView alloc] initWithFrame:(CGRectMake(0, 0, 10, 1))];
    self.messageTextField.leftViewMode = UITextFieldViewModeAlways;
    self.messageTextField.delegate = self;
    
    //通过通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(UIKeyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    
    
    [self.view addSubview:_tabelView];
    
    
  
    
    
    

}


//键盘回收
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self.messageTextField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField

{
    
    [textField resignFirstResponder];
    
    return YES;

    
}


- (void)UIKeyboardWillChangeFrame:(NSNotification *)noteInfo
{
    NSLog(@"adfadfasfdasfd");
    
    CGRect rect = [noteInfo.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    
    CGFloat keyBoradY = rect.origin.y;
    //平移的值
    CGFloat transFormValue = keyBoradY - screenH;
    
    //获取键盘弹出时间
    CGFloat keyboradDuration = [noteInfo.userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    [UIView animateWithDuration:keyboradDuration animations:^{
        
        self.view.transform = CGAffineTransformMakeTranslation(0, transFormValue);
    }];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)sendMessage:(id)sender {
    
    
    [_cr sendMessage:self.messageTextField.text callback:^(BOOL success, NSError *error) {
        if (success) {
            NSLog(@"发送消息成功");
        }else
        {
            NSLog(@"发送消息失败");
        }
    }];
    
    NSString *str =[AVUser currentUser].username ;
    NSString*str1 =[NSString stringWithFormat:@"%@ : %@",str,self.messageTextField.text];
    
    AVIMMessage * message = nil;
    message = [AVIMMessage messageWithContent:str1];
    if (message.content.length >= 200) {
        NSLog(@"您太长了");
        return;
    }
    [_messageArray addObject:message];
    
        [self.tabelView selectRowAtIndexPath:[NSIndexPath indexPathForRow:_messageArray.count - 1 inSection:0] animated:YES scrollPosition:(UITableViewScrollPositionBottom)];
    
    
   
    
    [self.tabelView reloadData];
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.messageArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:@"cell"];
    }
    
    cell.textLabel.text = [_messageArray[indexPath.row] valueForKey:@"content"]  ;
//    cell.Name.text = [AVUser currentUser].username ;
    
 [self.tabelView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messageArray.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    //AVIMMessageIOType ioType
    NSLog(@"````````````%@", [_messageArray[indexPath.row] valueForKey:@"ioType"] );
    
    if ( [_messageArray[indexPath.row] valueForKey:@"ioType"]  ) {
        cell.textLabel.text = @"";
         cell.detailTextLabel.text = [_messageArray[indexPath.row] valueForKey:@"content"]  ;
    
    }else {
        cell.detailTextLabel.text = @"";
        cell.textLabel.text = [_messageArray[indexPath.row] valueForKey:@"content"];
        
    }
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50 ;

}

//退出聊天室

-(void)quitAction:(UIBarButtonItem*)button
{
      [[ChatModel shareChatRoomHandle] logOut:^(BOOL success, NSError *error) {
         
          if (success) {
              [self.navigationController popViewControllerAnimated:YES];
          }else{
              
              UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"退出聊天室失败" preferredStyle:UIAlertControllerStyleAlert];
              
              UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
              }];
              [alert addAction:action];
              
          }
              
      }];
}


@end
